package priv.leetCode.thread.test1;

import lombok.extern.slf4j.Slf4j;

/*
 * 作者：m鹏h
 * 时间；2024/6/18 21:21
 * 描述：
 **/
@Slf4j
public class ThreadWait {

    private final Object lock = new Object();
    private boolean execute = false;


    public synchronized void test1() {
        this.execute = true;
        log.error("点了开始分拣按钮，其他接口不可以再往缓存集合中添加数据");
        try {
            Thread.sleep(5000);
            for (int i = 0; i < 10; i++) {
                log.error("数据库数据同步缓存数据中……  " + i);
            }
            log.error("数据库数据同步缓存数据中……");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        notifyAll();
        log.error("我操作完了 ，你们可以操作了。");
        this.execute = false;
    }

    public  void addDataTest(String data, Boolean isApple) {
        if (isApple) {
            synchronized (lock){
                // 如果第二个接口正在处理，则等待
                while (execute) {
                    try {
                       lock.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }

                TestThreadWait.getTestThreadWait().addData1(data);
        } else {
            log.error("点击了开始分拣按钮 ，同步订单信息从数据库到缓存中");
            synchronized (lock) {
                this.execute = true;
                for (int i = 0; i < 10; i++) {
                    try {
                        Thread.sleep(500);
                        TestThreadWait.getTestThreadWait().addData2(i + "  数据库数据同步缓存中");
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                log.error("数据库信息同步缓存订单完成！！！");
                this.execute = false;
                lock.notifyAll();
            }

        }
    }



    public static void main(String[] args) {
        ThreadWait sharedCollection = new ThreadWait();

        // 模拟MQ实时下发订单
        Thread firstInterfaceThread = new Thread(() -> {
            Integer i = 0;
            while (true) {
                try {
                    Thread.sleep(500);
                    sharedCollection.addDataTest("订单顺序号为"+i, true);
                    i++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });


        // 模拟点击了开始分拣按钮，去同步订单数据
        Thread secondInterfaceThread = new Thread(() -> {
            sharedCollection.addDataTest(null, false);
        }
        );

        // 启动线程
        firstInterfaceThread.start(); // MQ实时下发订单
        try {
            // 稍作等待，以确保第二个接口先开始处理
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        secondInterfaceThread.start(); // 点击开始分拣安按钮，数据库订单数据同步缓存

    }
}
